package cn.lysj.framework.common.security.jwt;

import cn.lysj.framework.common.annotation.CurrentCustomer;
import cn.lysj.framework.common.exception.MyException;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.customer.domain.Customer;
import cn.lysj.framework.customer.service.CustomerService;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

/**
 * @ Author ：drj.
 * @ Date  ：Created in 16:01 2018/11/12
 * @ Description:
 **/

public class CurrentCustomerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private CustomerService customerService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Customer.class)
                && parameter.hasParameterAnnotation(CurrentCustomer.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String customerId = (String) webRequest.getAttribute("id", RequestAttributes.SCOPE_REQUEST);
        Customer customer = null;
        if (!ParamUtil.isBlank(customerId)) {
            customer = customerService.findOne(customerId);
        }
        if (ParamUtil.isBlank(customer)) {
            throw new MyException("获取用户信息失败");
        }
        return customer;
    }
}
